﻿using CeremonyBackground.Infrastructure;
using CeremonyBackground.Models;
using CeremonyBackground.ViewModel;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CeremonyBackground.Tasks
{
    /// <summary>
    /// 同步用户服务
    /// </summary>
    public class CeremonySyncService
        : BackgroundService
    {
        private readonly BackgroundTasksDbContext _context;
        private readonly CSRedis.CSRedisClient _redisClient;
        private readonly BackgroundTaskSettings _settings;
        private readonly ILogger<CeremonySyncService> _logger;
        public CeremonySyncService(ILogger<CeremonySyncService> logger,
            BackgroundTasksDbContext context,
            IOptionsSnapshot<BackgroundTaskSettings> settings)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _context = context ?? throw new ArgumentException(nameof(context));
            _settings = settings.Value ?? throw new ArgumentNullException(nameof(settings));
            if (_redisClient == null)
            {
                _redisClient = new CSRedis.CSRedisClient(_settings.RedisTaskConnectionString);
                RedisHelper.Initialization(_redisClient);
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Run(async () => await Process(stoppingToken));
        }

        protected async Task Process(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
#if Marry
                    var msg = RedisHelper.BLPop(10, _settings.ChannelTaskName);
                    if (!string.IsNullOrEmpty(msg))
                    {


                        var record = JsonConvert.DeserializeObject<SubscribeUserPrizeRecord>(msg);
                        if (record != null)
                        {
                            if(record.Level <= 3 && record.Level > 0)
                            {
                                int overHeadOrder = 0;
                                switch (record.Level)
                                {
                                    case 1:
                                        overHeadOrder = 3;
                                        break;
                                    case 2:
                                        overHeadOrder = 2;
                                        break;
                                    case 3:
                                        overHeadOrder = 1;
                                        break;
                                    default:
                                        break;
                                }
                                string tag = string.IsNullOrEmpty(record.Tag) == true ? "" : "(" + record.Tag + ")";
                               await _context.WechatMoments.AddAsync(new Models.WechatMoment(overHeadOrder,
                                    record.UserId,
                                    string.Format("我摇中了{0}{1},快来为我点赞吧!", record.PrizeName, tag),
                                    record.ImageName));
                            }
                            await _context.UserPrizeRecords.AddAsync(new Models.UserPrizeRecord(record.UserId, record.PrizeId));
                            int result = await _context.SaveChangesAsync();
                            string resultStr = result > 0 ? "succeed" : "failed";
                            _logger.LogInformation("----- Sync UserPrizeRecord {Result}: {UserPrizeRecordViewModel}: ({@UserPrizeRecordViewModel})",
                                  resultStr,
                                  record.GetType().Name,
                                  record);
                        }

                }
#endif
                    var bobingUser = RedisHelper.BLPop<BobingUser>(10, _settings.ChannelTaskName);
                    if (bobingUser == null)
                        continue;
                    var dbUser = _context.BobingUsers.Where(t => t.AuthorizationCode == bobingUser.AuthorizationCode).FirstOrDefault();
                    //新增
                    if (dbUser == null)
                    {
                        await _context.BobingUsers.AddAsync(bobingUser);
                        int result = await _context.SaveChangesAsync();
                        string resultStr = result > 0 ? "成功" : "失败";
                        _logger.LogInformation("----- Sync BobingUsers {Result}: {BobingUsers}: ({@BobingUsers})",
                                 resultStr,
                                 bobingUser.GetType().Name,
                                 bobingUser);
                    }
                    else //更新
                    {
                        dbUser.UserName = bobingUser.UserName;
                        dbUser.IsRemove = bobingUser.IsRemove;
                        _context.Update(dbUser);
                        int result = await _context.SaveChangesAsync();
                        string resultStr = result > 0 ? "成功" : "失败";
                        _logger.LogInformation("----- update BobingUsers {Result}: {BobingUsers}: ({@BobingUsers})",
                                 resultStr,
                                 dbUser.GetType().Name,
                                 dbUser);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
    }
}
